@**
 * @Author: jipeng.Li
 * @Date: 2021-04-21 08:21:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-05-08 13:08:21
 * @Description: 核销成功
 */

import React, {Component} from "react";
import {
  BackHandler,
  Image,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from "react-native";
import {Button, DashLine, msg} from "@/common";
import {
  isAndroid,
  mainBgColorBlack,
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp,
} from "@/styles";
import {iconApplyGoldInsurance, iconSuccess} from "@/images";
import EditCardNoModal from "./components/edit-card-no-modal";
import oil from "@/api/oil";
import tool from "@/common/utils/getDate";
import Header from "@/common/header";
import BackImage from "@/common/back-image";

const Submit = Button.Submit;

export default class WriteOffSuccess extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pumpOilNo: '',
      editCarNo: '', // 修改的车牌
      writeOffAmount: 0,
      userDetails: null,
      oilDetails: null,
      isLoading: false,
      showEditCardNoModal: false,
    }
  }

  componentDidMount() {
    // 处理安卓物理返回键
    if (isAndroid) {
      BackHandler.addEventListener('hardwareBackPress', this.androidBack);
    }
    const navigation = this.props.navigation;
    const state = navigation.state || {};
    const params = state.params || {};
    const {pumpOilNo} = params;
    this.setState({pumpOilNo}, () => this.verificationSuccess());
  }

  componentWillUnmount() {
    clearTimeout(this.timeOut);
    if (isAndroid) {
      BackHandler.removeEventListener('hardwareBackPress', this.androidBack);
    }
  }

  render() {
    const {userDetails, oilDetails, showEditCardNoModal, writeOffAmount, editCarNo, isLoading} = this.state;
    return (
      <SafeAreaView style={{flex: 1}}>
        {this._renderHead()}
        <ScrollView style={{flex: 1, backgroundColor: mainBgColorLightGray}}>
          <View style={styles.successBrand}>
            <View style={styles.brandTextTips}>
              {isLoading || (
                <Image
                  source={iconSuccess}
                  style={{
                    width: px2dp(50),
                    height: px2dp(50)
                  }}
                />
              )}
              <Text style={styles.brandText}>{isLoading ? '核销中' : '核销成功'}</Text>
            </View>
            {isLoading || (
              <Text style={styles.brandText}>
                ¥<Text style={{fontSize: px2dp(64)}}>{writeOffAmount}</Text>
              </Text>
            )}
          </View>
          <View style={styles.details}>
            {userDetails && (
              Object.keys(userDetails).map((value, index) => {
                return (
                  <View key={`userDetailsLine${index}`} style={styles.detailsLine}>
                    <Text style={styles.lineText}>{`${value}：`}</Text>
                    {
                      value === '车牌号码' ? (
                        <TouchableOpacity
                          style={styles.carNoLine}
                          onPress={() => this.setState({showEditCardNoModal: true})}
                        >
                          <Text style={[styles.lineText]}>{editCarNo || userDetails[value]}</Text>
                          <Image
                            source={iconApplyGoldInsurance}
                            style={{
                              width: px2dp(16.2),
                              height: px2dp(16.2),
                              marginRight: px2dp(10)
                            }}
                          />
                        </TouchableOpacity>
                      ) : (
                        <Text style={[styles.lineText, {textAlign: 'right', flex: 1}]}>{userDetails[value]}</Text>
                      )
                    }
                  </View>
                )
              })
            )}
          </View>
          <DashLine/>
          <View style={styles.details}>
            {oilDetails && (
              Object.keys(oilDetails).map((value, index) => {
                return (
                  <View key={`oilDetailsLine${index}`} style={styles.detailsLine}>
                    <Text style={styles.lineText}>{`${value}：`}</Text>
                    <Text style={[styles.lineText, {textAlign: 'right', flex: 1}]}>{oilDetails[value]}</Text>
                  </View>
                )
              })
            )}
          </View>
          <View style={{alignItems: 'center'}}>
            <Submit
              text="继续核销"
              onClick={() => {
                msg.emit('router: refreshRoute', {
                  routeName: 'WriteOffForOil',
                });
                msg.emit('router: goToNext', {
                  routeName: 'WriteOffForOil',
                });
              }}
              boxStyle={styles.btnBoxStyle}
              btnTextStyle={{
                fontSize: px2dp(32),
              }}
            />
            <Submit
              text="核销记录"
              onClick={() => {
                msg.emit('router: goToNext', {
                  routeName: 'WriteOffRecord',
                });
              }}
              boxStyle={[styles.btnBoxStyle, {backgroundColor: mainBgColorWhite}]}
              btnTextStyle={{
                fontSize: px2dp(32),
                color: mainBgColorBlack
              }}
            />
          </View>
          <View style={{marginTop: px2dp(20), paddingHorizontal: px2dp(32)}}>
            <Text style={styles.tipsText}>
              <Text style={{color: 'red'}}>*</Text>
              {`温馨提示：\n \t如上方“车牌号码”与实际不符，请点击“车牌号码”及时修改！`}
            </Text>
          </View>
        </ScrollView>
        <EditCardNoModal
          isShow={showEditCardNoModal}
          changeIsShow={status => this.setState({showEditCardNoModal: status})}
          determine={cardNo => {
            this.setState({editCarNo: cardNo});
            this.resetCar(cardNo)
          }}
        />
      </SafeAreaView>
    );
  }

  _renderHead = () => {
    return (
      <Header
        renderLeft={() => (
          <TouchableOpacity
            activeOpacity={0.8}
            onPress={this.goBack}
            style={isAndroid ? {paddingVertical: px2dp(14), paddingHorizontal: px2dp(40)} :
              {paddingVertical: px2dp(14), paddingRight: px2dp(40)}}
          >
            <BackImage/>
          </TouchableOpacity>
        )}
        renderTitle={() => <Text style={{color: '#333232', fontWeight: 'bold', fontSize: px2dp(36)}}>核销成功</Text>}
      />
    )
  }

  goBack = () => {
    msg.emit('router: refreshRoute', {
      routeName: 'WriteOffForOil',
    });
    msg.emit('router: goToNext', {
      routeName: 'WriteOffForOil',
    });
  };

  androidBack = () => {
    this.goBack();
    return true;
  }

  // 是否核销成功
  // 接口返回： 0 等待扫码(页面不变化) 继续请求 | 1 扫码核销中 | 2 扫码异常 | 4 支付成功 | 6 余额不足
  verificationSuccess = () => {
    const {pumpOilNo} = this.state;
    this.setState({isLoading: true});
    this.timeOut && clearTimeout(this.timeOut);
    this.timeOut = setTimeout(() => {
      oil.getVerificationResult({pumpOilNo}).then(res => {
        const {status} = res.data;
        if (status === 4) {
          clearTimeout(this.timeOut);
          this.getVerificationDetail(pumpOilNo)
        } else {
          this.verificationSuccess();
        }
      })
    }, 2000);
  }

  getVerificationDetail = (pumpOilNo) => {
    oil.getVerificationDetail({pumpOilNo}).then(res => {
      if (res.success) {
        const {
          legalName,
          allianceName,
          balance,
          carownerName,
          driverName,
          driverMobile,
          carNo,
          empowerNum,
          empowerEndTime,
          oil,
          writeOffAmountPer,
          oilTime,
          oilCount,
          gunNo,
          stationName,
          writeOffAmount,
          type // type =2 挂账 type=1 配油
        } = res.data;

        let userDetails = {
          '法人名称': legalName,
          '商户名称': allianceName,
          '车主姓名': carownerName,
          '授权司机': `${driverName} ${driverMobile}`,
          '车牌号码': carNo || '无车牌',
        }

        // 挂账卡不显示剩余次数,到期时间,账户剩余金额
        if (type === 1) {
          userDetails = {
            ...userDetails,
            ...{
              '剩余次数': empowerNum !== null ? empowerNum : '无限次',
              '到期时间': empowerEndTime ? tool.dateForm(empowerEndTime, 'yyyy.MM.dd hh:mm:ss') : '',
              '账户剩余金额': `${balance}元`,
            }
          }
        }

        let oilDetails = {
          '油品名称': `${oil}#`,
          '油品单价': `${writeOffAmountPer}元 / 升`,
          '加油时间': oilTime ? tool.dateForm(oilTime, 'yyyy.MM.dd hh:mm:ss') : '',
          '加油升数': `${oilCount}升`,
          '加油枪号': `${gunNo}号`,
          '加油站点': stationName
        }

        this.setState({userDetails, oilDetails, writeOffAmount, isLoading: false});
      } else {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '错 误',
          text: '详情查询失败',
          okText: '退出',
          isClickBg: false,
          okFn: () => {
            msg.emit('router: refreshRoute', {
              routeName: 'WriteOffForOil',
            });
            msg.emit('router: goToNext', {
              routeName: 'WriteOffForOil',
            });
          },
        })
      }
    })
  }

  // 编辑车牌号
  resetCar = (carNo) => {
    const {pumpOilNo} = this.state;
    oil.resetCar({carNo, pumpOilNo}).then(res => {
      if (res.success) {
        msg.emit('app:tip', {text: '修改成功'});
        this.setState({showEditCardNoModal: false})
      } else {
        msg.emit('app:tip', {text: res.msg || '请求失败'});
      }
    })
  }
}

const styles = StyleSheet.create({
  successBrand: {
    backgroundColor: mainBgColorWhite,
    height: px2dp(226),
    alignItems: 'center',
    justifyContent: 'center'
  },
  brandTextTips: {
    flexDirection: 'row'
  },
  brandText: {
    fontSize: px2dp(40),
    fontWeight: 'bold'
  },
  details: {
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32)
  },
  detailsLine: {
    flexDirection: 'row',
    height: px2dp(26 + 32),
  },
  lineText: {
    fontSize: px2dp(26),
    color: '#999793',
    lineHeight: px2dp(26 + 32),
  },
  btnBoxStyle: {
    height: px2dp(80),
    borderRadius: px2dp(10),
    width: '80%',
    marginTop: px2dp(30),
  },
  tipsText: {
    color: '#999793',
    fontSize: px2dp(22)
  },
  carNoLine: {
    flex: 1,
    flexDirection: 'row-reverse',
    alignItems: 'center',
  }
})
